package cn.springcloud.fix.gateway.service.impl;

import cn.springcloud.fix.gateway.api.request.GatewayRouteAddRequest;
import cn.springcloud.fix.gateway.api.request.GatewayRouteUpdateRequest;
import cn.springcloud.fix.gateway.bo.RouteDefinitionBO;
import cn.springcloud.fix.gateway.dao.entity.GatewayRoute;
import cn.springcloud.fix.gateway.dao.mapper.GatewayRouteMapper;
import cn.springcloud.fix.gateway.service.RoutesService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class RoutesServiceImpl implements RoutesService {

    private GatewayRouteMapper gatewayRouteMapper;

    @Override
    public List<RouteDefinitionBO> getRouteDefinitions() {
        List<RouteDefinitionBO> routeDefinitions = new ArrayList<>();
        List<GatewayRoute> routes = gatewayRouteMapper.selectList(Wrappers.emptyWrapper());
        if (CollectionUtils.isEmpty(routes)) return routeDefinitions;

        for (GatewayRoute gatewayRoute : routes) {
            RouteDefinitionBO definitionBO = RouteDefinitionBO.assembleRouteDefinitionBO(gatewayRoute);
            routeDefinitions.add(definitionBO);
        }
        return routeDefinitions;
    }

    @Override
    public List<GatewayRoute> getRoutes() {
        List<GatewayRoute> routes = gatewayRouteMapper.selectList(Wrappers.emptyWrapper());
        if (CollectionUtils.isEmpty(routes)) {
            return new ArrayList<>();
        }
        return routes;
    }

    @Override
    public GatewayRoute getGatewayRouteById(Long id) {
        return gatewayRouteMapper.selectById(id);
    }

    @Override
    public int delete(Long id) {
        return gatewayRouteMapper.deleteById(id);
    }

    @Override
    public int addRoute(GatewayRouteAddRequest request) {
        GatewayRoute route = new GatewayRoute();
        route.setRouteId(request.getRouteId());
        route.setRouteUri(request.getRouteUri());
        route.setFilters(request.getFilters());
        route.setPredicates(request.getPredicates());
        return gatewayRouteMapper.insert(route);
    }

    @Override
    public int updateRoute(GatewayRouteUpdateRequest request) {
        GatewayRoute route = new GatewayRoute();
        route.setId(request.getId());
        route.setRouteId(request.getRouteId());
        route.setRouteUri(request.getRouteUri());
        route.setFilters(request.getFilters());
        route.setPredicates(request.getPredicates());
        return gatewayRouteMapper.updateById(route);
    }
}
